import {Command} from '../constant';
import {Dispatch} from 'typings';
import {getActionProxy} from '@/redux/action-util';
import api from 'api';
import * as reduxStore from '@/redux/store';
import Action from './action';
import pagesPackageACustomerReceiveAddressEditMain from '../reducers/main';
import {addressInfo} from '@/utils/location/area/area';

export default (dispatch: Dispatch) => {
  const actions = {
    action: getActionProxy<typeof Action>(Action)(dispatch),

    /**
     * 初始化数据
     */
    async init(tid, mode?: string, localKey?: string) {
      await actions.loadReducer();
      if (tid != '-1') {
        const res = await api.customerDeliveryAddressBaseController.findById(tid);
        let addressInfoStr;
        if (res.streetId != -1) {
          addressInfoStr = await addressInfo(res.provinceId, res.cityId, res.areaId, res.streetId);
        } else {
          addressInfoStr = await addressInfo(res.provinceId, res.cityId, res.areaId);
        }
        dispatch({
          type: Command.init,
          payload: {
            main: {
              consigneeName: res.consigneeName,
              consigneeNumber: res.consigneeNumber,
              deliveryAddress: res.deliveryAddress,
              isDefaltAddress: res.isDefaltAddress,
              deliveryAddressId: res.deliveryAddressId,
              areaInfo: addressInfoStr,
              areaIds: [res.provinceId, res.cityId, res.areaId, res.streetId],
              provinceId: res.provinceId,
              cityId: res.cityId,
              areaId: res.areaId,
              streetId: res.streetId,
              mode: mode,
              localKey: localKey,
            },
          },
        });
      }
    },
    /**
     * 重置
     */
    async clean() {
      //@ts-ignore
      __TARO_ENV !== 'h5' && (await actions.unloadReducer());
      dispatch({type: Command.clean});
    },

    /**
     * 动态添加注入reducer
     */
    async loadReducer() {
      reduxStore.registerReducer({
        pagesPackageACustomerReceiveAddressEditMain,
      });
    },

    /**
     * 卸载reducer
     */
    async unloadReducer() {
      if (reduxStore.deregister) {
        reduxStore.deregister(['pagesPackageACustomerReceiveAddressEditMain']);
      } else {
        console.error('请在redux/store中实现deregister逻辑. ');
      }
    },
  };

  return {actions};
};

//create by moon https://github.com/creasy2010/moon
